<template>
  <a-modal
      :visible="visible"
      title="编辑商品"
      @ok="handleOk"
      @cancel="handleCancel"
      :confirmLoading="confirmLoading"
  >
    <a-form :model="formState" :rules="rules" ref="formRef">
      <a-form-item name="name" label="商品名称">
        <a-input v-model:value="formState.name" />
      </a-form-item>
      <a-form-item name="price" label="价格">
        <a-input-number v-model:value="formState.price" :min="0" :step="0.01" style="width: 100%" />
      </a-form-item>
      <a-form-item name="image" label="图片URL">
        <a-input v-model:value="formState.image" />
      </a-form-item>
      <a-form-item name="descStatus" label="状态">
        <a-select v-model:value="formState.descStatus">
          <a-select-option value="在售">在售</a-select-option>
          <a-select-option value="下架">下架</a-select-option>
          <a-select-option value="已售出">已售出</a-select-option>
        </a-select>
      </a-form-item>
    </a-form>
  </a-modal>
</template>

<script setup>
import { ref, reactive, watch } from 'vue';
import { useProductStore } from "@/stores/index.js";
import {message} from "ant-design-vue";

const props = defineProps({
  visible: Boolean,
  product: Object,
});

const emit = defineEmits(['update:visible', 'success']);

const productStore = useProductStore();

const formRef = ref(null);
const confirmLoading = ref(false);

const formState = reactive({
  id: '',
  name: '',
  price: 0,
  image: '',
  descStatus: '在售',
});

const rules = {
  name: [{ required: true, message: '请输入商品名称' }],
  price: [{ required: true, message: '请输入价格' }],
  image: [{ required: false, message: '请输入图片URL' }],
  descStatus: [{ required: true, message: '请选择状态' }],
};

watch(() => props.product, (newProduct) => {
  if (newProduct) {
    Object.assign(formState, newProduct);
  }
}, { immediate: true });

const handleOk = async () => {
  if (formState) {
    const success = await productStore.reviseProducts(formState);
    if (success) {
      message.success("编辑成功");
      emit('update:visible', false);
    } else {
      console.log("编辑商品数据失败", productStore.error);
    }
  } else {
    console.log('表单为空哦');
  }
};

const handleCancel = () => {
  emit('update:visible', false);
};
</script>